<template>
  <div class="webchat_set_box">
    <div class="end_session_category">
      <div class="searchBox">
        <span class="todo_btn" @click="addOne"><i class="iconfont icon-zhankai"></i>  {{$t('config.channel.addOneEmailEnd')}}</span>
        <span class="todo_btn" @click="refreshTable"><i class="iconfont icon-shuaxin"></i>{{$t('public.refresh')}}</span>
        <span @click.stop="importLabel" style="padding-right: 10px; cursor: pointer"><i class="icon iconfont icon-daoru"></i>{{$t('config.customer.import')}}</span>
        <span @click.stop="exoprtLabel" v-if="isExportExcel" style="padding-right: 10px; cursor: pointer"><i class="icon iconfont icon-daochu1"></i>{{$t('webchat.exportSessionRecord')}}</span>
        <el-select v-model="screening" @change="selectStatus">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <el-input
          v-show="isShowInput"
          :placeholder="$t('configLazyLoad.channel.placeholderNameSeach')"
          size="mini"
          class="condition"
          v-model="searchLabelName"
          @keyup.enter.native="searchLabel">
          <i
            class="el-input__icon el-icon-search"
            slot="suffix"
            @click="searchLabel">
          </i>
        </el-input>
      </div>
      <end-session-tree-table
        ref="endseeion"
        :tableData="tableData"
        :searchLabelName="searchLabelName"
        :searchLabelRandom="searchLabelRandom"
        :doAddRandom="doAddRandom"
        :screening="screening"
        v-if="tableLoading && tableData.length <= 500"
        @delete="deleteLabel"
        :refreshflag="refreshflag"
        @save="saveLabel"
        @reset="reset"
        >
      </end-session-tree-table>
      <EndSessionTreeTableNew
        ref="endseeion"
        :tableData="tableData"
        :searchLabelName="searchLabelName"
        :searchLabelRandom="searchLabelRandom"
        :doAddRandom="doAddRandom"
        :screening="screening"
        v-if="tableLoading && tableData.length > 500"
        @delete="deleteLabel"
        :refreshflag="refreshflag"
        @save="saveLabel"
        @reset="reset"
        >
      </EndSessionTreeTableNew>
    </div>
    <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll title="导入在线结束会话类型" :visible.sync="importLabelDialog" width="50%">
      <div class="btn-wrap">
        <el-button type="info" class="temp-download primary_btn">
          <a href="/static/template/webchat_label_template.xlsx" download>{{$t('km.downloadImport')}}</a>
        </el-button>
        <!--饿了么上传组件-->
        <el-upload
          class="temp-upload"
          :action="uploadUrl"
          accept=".xls,.xlsx"
          name="upload"
          :data="uploadHeaders"
          :with-credentials="true"
          :on-success="handleSuccess"
          :on-error="handleError"
          :before-upload="beforeUpload"
          :show-file-list="false">
          <el-button class="primary_btn" type="primary">{{$t('km.importName')}}</el-button>
        </el-upload>
      </div>
      <div class="import" v-show="importShow">
        <el-row :gutter="20">
          <el-col :span="4" class="label">{{$t('km.batchNo')}}</el-col>
          <el-col :span="10"><el-input v-model.trim="importObj.batchNo" :disabled="true"></el-input></el-col>
          <el-col :span="10"><el-input v-model.trim="importObj.batchRemark" @click.enter="importExcel" :placeholder="$t('km.batchNoMark')"></el-input></el-col>
        </el-row>
        <el-button class="primary_btn margin-t" @click.stop="importExcel" type="primary">{{$t("config.customer.import")}}</el-button>
      </div>
      <div class="instructions" v-html="$t('km.importTips2')" v-once></div>
    </el-dialog>
  </div>
</template>
<script>
  import EndSessionTreeTable from './webchatEndSessionTree.vue'
  import EndSessionTreeTableNew from './webchatEndSessionTreeNew.vue'
  import { deepClone, getDateNo, isHasMenu } from '@/utils/m7Utils.js'
  import * as uuid from 'uuid'
  function getDicByType (store, data) {
    let dataNew = {
      type: data
    }
    return store.dispatch('getDicByType', dataNew)
  }
  function delDicItem (store, data) {
    let dataNew = {
      key: data.data.key,
      level: data.data.levelStr,
      _id: data._id
    }
    return store.dispatch('delDicItem', dataNew)
  }
  function saveDic (store, data) {
    let dataNew = {
      _id: data._id,
      type: 'webchat',
      key: data.data.key,
      lastLevel: data.data.lastLevel,
      level: data.data.levelStr,
      name: data.data.name,
      flag: data.data.flag,
    }
    if (data.data.state) {
      dataNew.state = data.data.state
    }
    if (!dataNew.key) {
      dataNew.key = uuid.v1()
      dataNew.flag = 'add'
      dataNew.level = dataNew.lastLevel ? dataNew.lastLevel + '_0' : '0'
    }
    if (dataNew.name) {
      return store.dispatch('saveDicItem', dataNew)
    } else {
      return false
    }
  }
  export default{
    name: 'webchatEndSessionCategory',
    data () {
      return {
        isExportExcel: false, // 是否有导出配置权限
        importLabelDialog: false,
        importShow: false,
        uploadUrl: '/fileUpload',
        uploadHeaders: {
          type: 'undefined',
          module: '',
          sessionId: this.$store.state.session.sessionId
        },
        // 导入请求参数
        importObj: {
          batchNo: '',
          batchRemark: ''
        },
        searchLabelName: '',
        isShowInput: true,
        tableData: [],
        doAddRandom: 0,
        tableLoading: false,
        refreshflag: 0,
        _id: '',
        tableDataClone: [],
        tableDataReal:[],
        searchLabelRandom: 0,
        screening: 'open',
        options: [
          {label: '全部', value: 'all'},
          {label: '启用', value: 'open'},
          {label: '停用', value: 'close'}
        ]
      }
    },
    methods: {
      // 上传前 配置上传参数
      beforeUpload (file) {
        this.uploadHeaders.key = 'file'
        this.uploadHeaders.name = file.name
        let arr = file.name.split('.')
        let arrType = ['xls', 'xlsx']
        if (arrType.indexOf(arr[arr.length - 1]) !== -1) {
          return true
        } else {
          this.$message.error(this.$t('km.fileTypeError'))
          return false
        }
      },
      //      上传成功
      handleSuccess (response) {
        if (response.success) {
          this.importObj.batchNo = getDateNo()
          this.importObj.batchRemark = ''
          this.importObj.fileName = response.filePath ? response.filePath.substring(response.filePath.lastIndexOf('/') + 1) : ''
          this.importObj.trueName = response.fileName || ''
          this.importShow = true
        } else {
          this.$message.error(this.$t('message.default_tips'))
        }
      },
      //      失败
      handleError () {
        this.$message.error(this.$t('message.default_tips'))
      },
      // 导入请求
      importExcel () {
        this.$store.dispatch('importWebchatLabel', this.importObj).then((resp) => {
          if (resp.success) {
            this.$message.success(this.$t('channelsettings.webchatLabel12'))
            this.importShow = false
            this.importLabelDialog = false
            setTimeout(() => { // 延时一下，导入异步
              this.refreshTable()
            }, 400)
          }
        })
      },
      importLabel () {
        this.importObj = {batchNo: '', batchRemark: ''}
        this.importShow = false
        this.importLabelDialog = true
      },
      exoprtLabel () {
        let data = {
          Method: 'exportImFinishKey',
          Query: {}
        }
        this.$store.dispatch('exportXls', data).then((res) => {
          if (res.success) {
            this.$message.success(this.$t('webchat.exportSuccess'))
          }
        })
      },
      addOne () {
        this.doAddRandom = Math.random()
      },
      refreshTable () {
        this.searchLabelName = ''
        let that = this
        getDicByType(that.$store, 'webchat').then((res) => {
          if (res.row && res.row.options.length) {
            that.handleLabel(res.row.options)
            that.refreshflag = Math.random()
          }
          if (res.row && res.row._id) {
            that._id = res.row._id
          }
          this.tableLoading = true
          this.selectStatus(this.screening)
        })
      },
      handleLabel (data) {
        this.tableLoading = false
        this.tableData = []
        this.handleTableData({arr: data, level: 1, keyStr: 'webchat_', levelStr: '', lastLevel: ''})
        this.tableLoading = true
        this.tableDataReal = deepClone(this.tableData)
      },
      // screeningFun (val) {
      //   console.log(val)
      //   this.tableData.filter(item => {
      //     return
      //   })
      // },
      handleTableData (data) {
        let time = data.level
        time++
        for (let i = 0; i < data.arr.length; i++) {
          let levelStr = data.levelStr
          let lastLevel = data.lastLevel
          let keyStr = data.keyStr
          let item = data.arr[i]
          keyStr += i + '-'
          let newKeyStr = keyStr
          newKeyStr = newKeyStr.substring(0, newKeyStr.length -1)
          var obj = {
            keyStr: newKeyStr,
            key: item.key,
            level: data.level,
            stateShow: item.state || '2',
            name: item.name,
            status: false,
            flag: false
          }
          let newLastLevel = levelStr
          newLastLevel = newLastLevel.substring(0, newLastLevel.length -1)
          obj.lastLevel = newLastLevel
          levelStr += i + '_'
          let newLevelStr = levelStr
          newLevelStr = newLevelStr.substring(0, newLevelStr.length -1)
          obj.levelStr = newLevelStr
          this.tableData.push(obj)
          if (item.options && item.options.length > 0) {
            this.handleTableData({arr:item.options, level: time, lastLevel: newLevelStr, keyStr: keyStr, levelStr: levelStr})
          }
        }
      },
      deleteLabel (data) {
        let _id = this._id
        let that = this
        that.tableDataClone = deepClone(that.tableData)
        delDicItem(that.$store, {data: data, _id: _id}).then((res) => {
          if (res.success) {
            that.handleLabel(res.row.options)
            that.refreshflag = Math.random()
          }
        })
      },
      saveLabel (data, flag) {
        if (!data.name) {
          this.$message(this.$t('configLazyLoad.channel.endSessionCannotNull'))
          return
        }
        let that = this
        let _id = this._id
        that.tableDataClone = deepClone(that.tableData)
        if (flag) {
          data.state = flag === 'open' ? '2' : '1'
          data.flag = 'changeState'
        } else {
          data.flag = 'update'
        }
        // console.log(data,flag)
        // return
        saveDic(that.$store, {data: data, _id: _id}).then((res) => {
          if (res.success) {
            that.handleLabel(res.row.options)
            // that.selectStatus(this.screening,true)
            let arr = that.tableDataClone
            let newArr = that.tableData
            // let min = Math.min(arr.length,newArr.length)
            for (let i = 0; i < arr.length; i++) {
              if(arr[i]&&newArr[i]&&arr[i].key === newArr[i].key){
                newArr[i].flag = arr[i].flag
              }
            }
            that.refreshflag = Math.random() + 1
            if (!_id) {
              this.refreshTable()
            }
            if(data.level === 1 && data.flag == 'update'){
              this.screening = 'open'
              this.searchLabelName = ''
              this.selectStatus(this.screening)
            }else{
              this.selectStatus(this.screening)
            }
            if(flag === "open" && this.screening == "close") this.selectStatus(this.screening)
            if(this.screening == "open" && flag == 'stop')  this.selectStatus(this.screening)
          }
        })
      },
      searchLabel () {
        this.searchLabelRandom = Math.random()
      },
      selectStatus(val,flag){
        let data = []
        let ids = []
        let number = -1
        let newArr = [...this.tableDataReal]
        let arr = [...this.tableData]
        for (let i = 0; i < arr.length; i++) {
          if(arr[i]&&newArr[i]&&arr[i].key === newArr[i].key){
            newArr[i].flag = arr[i].flag
          }
        }
        if(val === 'close'){
          data = newArr.filter(item=>{
            if(item.level === 1 && item.stateShow === '1'){
              ids.push(item.keyStr[8])
              return true
            }
            if(item.level !== 1){
              if(ids.indexOf(item.keyStr[8]) > -1) return true
            }
          })
        }else if(val === 'open'){
          data = newArr.filter((item,index)=>{
            if(item.stateShow === '1')return false
            return true
          })
        }else{
          data = newArr
        }
        this.tableData = data
        if (this.$refs.endseeion) {
          this.$refs.endseeion.refreshTable()
        }
      },
      reset(){
        this.screening = "open"
        this.selectStatus('open')

      }
    },
    components: {
      EndSessionTreeTable,
      EndSessionTreeTableNew
    },
    beforeMount () {
      this.refreshTable()
      // 导出权限设置
       if (isHasMenu('func_export_finishKey', this.$store.state.session.user) || this.$store.state.session.user.isAdmin) {
        this.isExportExcel = true
      }
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
  .end_session_category
    height calc(100% - 46px)
    overflow-y auto
  .searchBox
    height 34px
    padding 6px 10px
    line-height 34px
    .iconfont
      color $c-main
      font-size 12px
      border none
      padding 0
      margin-right 6px
  .condition
    width 200px
    float right

  .todo_btn
    cursor pointer
    margin-right 20px
    i
      color $c-main
  .btn-wrap
    padding-bottom 10px
    overflow hidden
    .temp-download
      float left
      a
        color #fff
    .temp-upload
      float left
      display inline-block
      margin-left 20px
    .temp-upload-btn
      font-size 12px
      padding 8px 15px    
</style>

